// 负责登录与注册
const express = require('express');
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const passport = require('passport');

const User = require ("../../models/User");

// 注册接口
router.post('/register', (req, res) => {
    // 查询数据库中是否有邮箱
    User.findOne({email: req.body.email}).then((user) => {
        if(user) {
            return res.status(400).json( "邮箱已被注册");
        }else {
            const newUser = new User({
                name:req.body.name,
                email:req.body.email,
                password:req.body.password,
                identity:req.body.identity
            });
            
            bcrypt.genSalt(10, function (err, salt) {
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if(err) throw err;
                    newUser.password = hash;
                    newUser.save().then(user => res.json(user)).catch(err => console.log(err));
                })

            })
        }
    })
});

// post api/users/login 返回token jwt passport
router.post('/login', (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    // 查询数据
    User.findOne({email}).then(user => {
        if (!user) {
            return res.status(404).json('用户不存在');
        }else {
            // 密码匹配
            bcrypt.compare(password, user.password).then(isMatch => {
                if(isMatch) {
                    const rule = {id:user.id, name:user.name, identity: user.identity};
                    // 第一个参数为规则 第二个为加密名称 第三个为过期时间 第四个为对应的箭头函数
                    jwt.sign(rule, 'secret', {expiresIn: 3600}, (err, token) => {
                        res.json({
                            success:true,
                            token:'Bearer ' + token
                        });
                    } );
                }else {
                    return res.status(400).json('密码错误!')
                }
            })
        }
    })
});

// get api/users/current  返回用户信息 private
router.get('/current', passport.authenticate('jwt', {session: false}) , (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        identity: req.user.identity
    });
});

module.exports = router;